package com.movies.service.controller.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.movies.service.common.Constants;
import com.movies.service.common.Result;
import com.movies.service.entity.Comment;
import com.movies.service.service.CommentService;
import com.movies.service.mapper.CommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/admin/comment")
@SaCheckLogin
@SaCheckRole("ADMIN")
public class AdminCommentController {

    @Autowired
    private CommentService commentService; // 仅分页
    @Autowired
    private CommentMapper commentMapper;   // 原生 SQL CRUD

//    分页查询评论列表（支持按用户/电影/最小评分筛选）
    @GetMapping("/page")
    public Result page(@RequestParam(defaultValue = "1") Integer pageNo,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) String uname,
                       @RequestParam(required = false) String mname,
                       @RequestParam(required = false) Double minScore) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(uname != null && !uname.trim().isEmpty(), Comment::getUname, uname)
                .like(mname != null && !mname.trim().isEmpty(), Comment::getMname, mname)
                .ge(minScore != null, Comment::getScore, minScore);
        Page<Comment> page = commentService.page(new Page<>(pageNo, pageSize), wrapper);
        return Result.success("查询成功", page);
    }

//    根据ID获取评论详情
    @GetMapping("/{id}")
    public Result get(@PathVariable Long id) {
        return Result.success(commentMapper.selectCommentById(id));
    }

//    新增评论
    @PostMapping("/create")
    public Result create(@RequestBody Comment comment) {
        int rows = commentMapper.insertComment(comment);
        return rows > 0 ? Result.success("新增成功") : Result.error(Constants.CODE_600, "新增失败");
    }

//    更新评论
    @PutMapping("/update")
    public Result update(@RequestBody Comment comment) {
        int rows = commentMapper.updateCommentById(comment);
        return rows > 0 ? Result.success("更新成功") : Result.error(Constants.CODE_600, "更新失败");
    }

//    删除评论
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        int rows = commentMapper.deleteCommentById(id);
        return rows > 0 ? Result.success("删除成功") : Result.error(Constants.CODE_600, "删除失败");
    }

//    批量删除评论
    @DeleteMapping("/batch")
    public Result deleteBatch(@RequestBody List<Long> ids) {
        int rows = commentMapper.deleteCommentsByIds(ids);
        return rows > 0 ? Result.success("批量删除成功") : Result.error(Constants.CODE_600, "批量删除失败");
    }
}